package com.partners.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.partners.constant.ErrorMessageEnum;
import com.partners.dao.basic.UserRoleDao;
import com.partners.dao.dto.RoleInputDTO;
import com.partners.dao.basic.PermissionDao;
import com.partners.dao.basic.RoleDao;
import com.partners.dao.basic.RolePermissionDao;
import com.partners.dao.bo.RoleDO;
import com.partners.dao.bo.RolePermissionDO;
import com.partners.dao.dto.RoleUserOutputDTO;
import com.partners.model.BusinessException;
import com.partners.model.Paging;
import com.partners.service.RoleService;
import com.partners.utils.TimestampUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author liangyongle
 * @date 2018-12-07
 */
@Service
@Slf4j
public class RoleServiceImpl implements RoleService {


    @Resource
    private RoleDao roleDao;

    @Resource
    private UserRoleDao userRoleDao;


    @Resource
    private PermissionDao permissionDao;

    @Resource
    private RolePermissionDao rolePermissionDao;
    private List<Integer> perArr;


    /**
     * 获取角色列表
     * @param paging Paging
     * @return Object
     *
    * */
    @Override
    public Map<String,Object> getRoleList(Paging paging, String name) {
        PageHelper.startPage(paging.getPage(),paging.getRows());
        Map<String,Object> allList = new HashMap<>();
        List<Map<String, Object>> list = roleDao.getRoleList(name);
        Page page = (Page) list;
        Object total  = page.getTotal();
        allList.put("total",total);
        allList.put("list",list);
        return allList;
    }

    /**
     * 获取角色详情
     * @param Id String
     * @return Object
     * */
    @Override
    public Map<String,Object> getRoleDetail(Integer Id) {
        RoleDO role = roleDao.selectByPrimaryKey(Id);
        Map<String,Object> list = new HashMap<>();
        list.put("detail",role);
        List<Map<String, Object>> permissionList = permissionDao.getPermissionList();
        if(permissionList !=null){
            List<Integer> rolePermission = permissionDao.getRolePermission(Id);
            for(Map<String,Object> map:permissionList){
                Integer selected = 0;
                if(rolePermission.contains((Integer) map.get("id"))){
                    selected = 1;
                }
                map.put("selected",selected);
            }
           list.put("per_list",permissionList);
        }


        return list;
    }


    /**编辑角色
     * @param roleInputDTO RoleInputDTO
     * @return Integer
     *
     * */
    @Override
    @Transactional
    public void editRole(RoleInputDTO roleInputDTO) {
        Integer exist = roleDao.getRoleByName(roleInputDTO.getName(),roleInputDTO.getPid(),roleInputDTO.getId());
        if(exist != null){
            throw BusinessException.of(ErrorMessageEnum.NAME_IS_EXIST);
        }
        RoleDO roleDO = new RoleDO();
        roleDO.setPid(roleInputDTO.getPid());
        roleDO.setName(roleInputDTO.getName());
        if(roleInputDTO.getId() != null){
            //修改
            roleDO.setId(roleInputDTO.getId());
            roleDao.updateByPrimaryKeySelective(roleDO);
            //删除所有的权限绑定
            rolePermissionDao.deleteByPrimaryKey(roleInputDTO.getId());
            List<Integer> perList = roleInputDTO.getPerList();
            if(perList != null) {
                List<Map<String,Integer>> permission = permissionDao.getPermissionListByPid(perList);
                List<Integer> perArr = permission.stream().map(item -> item.get("id")).collect(Collectors.toList());
                perList.addAll(perArr);
                log.info("perList{}",perList);
                RolePermissionDO rolePermissionDO = new RolePermissionDO();
                for (Integer pid:perList) {
                    rolePermissionDO.setPid(pid);
                    rolePermissionDO.setRoleId(roleInputDTO.getId());
                    rolePermissionDO.setAddtime(TimestampUtils.timestamp());
                    rolePermissionDao.insert(rolePermissionDO);
                }
            }
        }else{
            //新增
            roleDO.setAddtime(TimestampUtils.timestamp());
            roleDao.insert(roleDO);
            Integer newId = roleDO.getId();
            //新增权限列表
            List<Integer> perList = roleInputDTO.getPerList();
            if(perList != null) {
                List<Map<String,Integer>> permission = permissionDao.getPermissionListByPid(perList);
                List<Integer> perArr = permission.stream().map(item -> item.get("id")).collect(Collectors.toList());
                perList.addAll(perArr);
                RolePermissionDO rolePermissionDO = new RolePermissionDO();
                for (Integer pid:perList) {
                    rolePermissionDO.setPid(pid);
                    rolePermissionDO.setRoleId(newId);
                    rolePermissionDO.setAddtime(TimestampUtils.timestamp());
                    rolePermissionDao.insert(rolePermissionDO);
                }
            }
        }
    }

    /**删除角色
     * @param id Integer
     * @return Integer
     *
     * */
    @Override
    public Integer deleteRole(Integer id) {
        RoleDO role = roleDao.selectByPrimaryKey(id);
        if(role == null){
            throw BusinessException.of(ErrorMessageEnum.RECORD_NOT_FOUND);
        }
        //如果该角色有员工，不能删除
        Integer userRole = userRoleDao.selectByRoleId(id);
        if(userRole !=0){
            throw BusinessException.of(ErrorMessageEnum.ROLE_HAS_USER);
        }

        Integer result = roleDao.deleteByPrimaryKey(id);
        rolePermissionDao.deleteByPrimaryKey(id);
        return result;
    }

    /**
    * 获取指定的角色下面的角色列表
     * @param pid
     * return list
    * */
    @Override
    public Map<String,Object> getMyRoleList(Paging paging,Integer pid) {
        PageHelper.startPage(paging.getPage(),paging.getRows());
        Map<String,Object> allList = new HashMap<>();
        List<Map<String, Object>> list = roleDao.getMyRoleList(pid);
        for (Map<String,Object> map : list){
            Integer num = roleDao.getRoleTotal((Integer) map.get("id"));
            map.put("total",num);
        }
        Page page = (Page) list;
        Object total  = page.getTotal();
        allList.put("total",total);
        allList.put("list",list);
        return allList;
    }


    /**
     * 获取角色下面的用户
     * @return
     */
    @Override
    public Map<String, Object> getRoleUserList(Paging paging, Integer id) {
        RoleDO role = roleDao.selectByPrimaryKey(id);
        if(role == null){
            throw BusinessException.of(ErrorMessageEnum.ROLE_NOT_FOUND);
        }
        PageHelper.startPage(paging.getPage(),paging.getRows());
        Map<String,Object> allList = new HashMap<>();
        allList.put("title",role.getName());
        List<RoleUserOutputDTO> list = roleDao.getRoleUserList(id);
        log.info("list{}",list);
        Page page = (Page) list;
        Object total  = page.getTotal();
        allList.put("total",total);
        allList.put("list",list);

        return allList;
    }
}
